package com.jdd.modules.parkcar.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.RestTemplateVo;
import com.jdd.common.api.vo.Result;
import com.jdd.common.api.vo.ResultVo;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.*;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.parkWhiteEdit.entity.ParkWhiteEditList;
import com.jdd.modules.parkWhiteEdit.service.IParkWhiteEditListService;
import com.jdd.modules.parkcar.entity.CloudSynParkSpaceVo;
import com.jdd.modules.parkcar.entity.ParkCarMonthly;
import com.jdd.modules.parkcar.entity.ParkSpace;
import com.jdd.modules.parkcar.service.IParkCarMonthlyService;
import com.jdd.modules.parkcar.service.IParkSpaceService;
import com.jdd.modules.parkcar.vo.ParkSpaceBindPlateNoVO;
import com.jdd.modules.parking.entity.ConfigParkInfo;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IConfigParkInfoService;
import com.jdd.modules.parking.service.IParkInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author liuyaowen
 * @Description: 车位信息
 * @date 2021-06-01
 */
@Slf4j
@Api(tags = "车位管理")
@RestController
@RequestMapping("/parkCar/parkNumber")
public class ParkNumberController {

    @Resource
    private IParkCarMonthlyService parkCarMonthlyService;
    @Resource
    private IParkSpaceService parkSpaceService;
    @Resource
    private IParkWhiteEditListService parkWhiteEditListService;
    @Resource
    private ExecutorService executorService;
    @Resource
    private IConfigParkInfoService configParkInfoService;
    @Resource
    private IParkInfoService parkInfoService;

    @Value("${parkInfo.parkCode}")
    public String parkCode;


    public String appScrect;





    public String appId;

    @Resource
    private RestTemplateUtils restTemplateUtils;

    private final int PARK_SPACE_BIND_MAX_NUMBER = 8;
    private final int ERROR_CODE_500 = 500;
    @AutoLog(value = "车位管理-查询车位列表")
    @ApiOperation(value = "车位管理-查询车位列表", notes = "车位管理-查询车位列表")
    @RequestMapping(value = "/newlist")
    public Result<IPage<ParkSpace>> newlist(ParkSpace parkSpace,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            HttpServletRequest req) {
    	Result<IPage<ParkSpace>> result = new Result<IPage<ParkSpace>>();

        Page<ParkSpace> page = new Page<ParkSpace>(pageNo, pageSize);
        IPage<ParkSpace> pageList = parkSpaceService.getParkSpacePageList(parkSpace,page);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "车位管理-新增车位")
    @ApiOperation(value = "车位管理-新增车位", notes = "车位管理-新增车位")
    @PostMapping(value = "/addNew")
    @OperationLogDetail(detail = "车位管理，车位新增", level = LogLevelType.ONE, operationType = OperationType.INSERT, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> addNew(@RequestBody ParkSpace parkSpace) {
        return parkSpaceService.addNew(parkSpace);
    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车位管理-通过id删除车位")
    @ApiOperation(value = "车位管理-通过id删除", notes = "车位管理-通过id删除")
    @DeleteMapping(value = "/deleteNew")
    @OperationLogDetail(detail = "车位管理，车位通过id删除", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> deleteNew(@RequestParam(name = "id", required = true) String id) {
        return parkSpaceService.deleteNew(id);
    }
    @AutoLog(value = "车位管理-查询车位列表")
    @ApiOperation(value = "车位管理-查询车位列表", notes = "车位管理-查询车位列表")
    @RequestMapping(value = "/list")
    public Result<?> list(ParkCarMonthly parkCarMonthly,
                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                          HttpServletRequest req) {
        Result<IPage<ParkSpace>> result = new Result<>();
        String[] plateNo = req.getParameterMap().get("plateNo");
        String plateNoStr = null != plateNo ? plateNo[0] : null;
        if (StringUtils.isNotBlank(plateNoStr)) {
            //条件查询
            QueryWrapper<ParkCarMonthly> queryWrapper = QueryGenerator.initQueryWrapper(parkCarMonthly, req.getParameterMap());
            //按eq查询车牌和按照条件查询的列表
            List<ParkCarMonthly> list = parkCarMonthlyService.list(queryWrapper);
            //模糊车牌号查询
            QueryWrapper<ParkCarMonthly> monthlyQueryWrapper = new QueryWrapper<>();
            monthlyQueryWrapper.like("plate_no", plateNoStr);
            //模糊车牌号列表
            List<ParkCarMonthly> havaMonthList = parkCarMonthlyService.list(monthlyQueryWrapper);
            //车牌模糊与条件查询的去重的集合
            List<ParkCarMonthly> collect = Stream.of(list, havaMonthList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            //假如有多个编号相同的车位，将相同的车位再次去重
            List<String> parkNumberList = collect.stream().map(ParkCarMonthly::getParkNumber).distinct().collect(Collectors.toList());
            //根据编号再次查询
            LambdaQueryWrapper<ParkSpace> parkSpaceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            for (String parknumber : parkNumberList) {
                parkSpaceLambdaQueryWrapper.or().eq(ParkSpace::getParkNumber, parknumber);
            }
            Page<ParkSpace> page = new Page<>(pageNo, pageSize);
            IPage<ParkSpace> iPage = parkSpaceService.page(page, parkSpaceLambdaQueryWrapper);
            result.setSuccess(true);
            result.setResult(iPage);
        } else {
            ParkSpace parkSpace = new ParkSpace();
            BeanUtils.copyProperties(parkCarMonthly, parkSpace);
            QueryWrapper<ParkSpace> parkSpaceQueryWrapper = QueryGenerator.initQueryWrapper(parkSpace, req.getParameterMap());
            Page<ParkSpace> page = new Page<>(pageNo, pageSize);
            IPage<ParkSpace> iPage = parkSpaceService.page(page, parkSpaceQueryWrapper);
            result.setSuccess(true);
            result.setResult(iPage);
        }
        return result;
    }
    @AutoLog(value = "车位管理-查询车场可用的月租车位列表")
    @ApiOperation(value = "车位管理-查询车场可用的月租车位列表",notes = "车位管理-查询车场可用的月租车位列表")
    @RequestMapping(value = "/getParkFreeSpace")
    public Result<List<ParkSpace>> getParkFreeSpace(ParkSpace parkSpace)
    {
        Result<List<ParkSpace>> result = new Result<>();
        QueryWrapper<ParkSpace> queryWrapper = new QueryWrapper<>(parkSpace);
        if(StringUtils.isNotBlank(parkSpace.getPermissionId()))
        {
            List<ParkSpace> list = parkSpaceService.getFreeSpaces(parkSpace.getPermissionId());
            result.setSuccess(true);
            result.setResult(list);
            return result;
        }
        queryWrapper.lambda().isNull(ParkSpace::getMonthlyCardId);
        List<ParkSpace> list = parkSpaceService.list(queryWrapper);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }
    @AutoLog(value = "车位管理-查询当前车位绑定的车牌号集合")
    @ApiOperation(value = "车位管理-查询当前车位绑定的车牌号集合", notes = "车位管理-查询当前车位绑定的车牌号集合")
    @PostMapping(value = "/queryCarList")
    public Result<?> queryCarList(@RequestBody ParkSpace parkSpace) {
        Result<List<ParkCarMonthly>> result = new Result<>();
        LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkCarMonthly::getParkNumber, parkSpace.getParkNumber());
        List<ParkCarMonthly> list = parkCarMonthlyService.list(queryWrapper);
        result.setResult(list);
        return result.success("查询成功");
    }

    @AutoLog(value = "车位管理-新增车位")
    @ApiOperation(value = "车位管理-新增车位", notes = "车位管理-新增车位")
    @PostMapping(value = "/add")
    @OperationLogDetail(detail = "车位管理，车位新增", level = LogLevelType.ONE, operationType = OperationType.INSERT, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> add(@RequestBody ParkSpace parkSpace) {
        Result<?> result = new Result<>();
        if (StringUtils.isEmpty(parkSpace.getParkNumber()) || parkSpace.getParkNumber().length() > 10) {
            return result.error500("车位编号信息不合法！！");
        }
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        parkSpace.setId(SnowFlakeUtil.getId());
        parkSpace.setParkName(loginUser.getParkName());
        parkSpace.setCreateUser(loginUser.getUsername());
        parkSpace.setCreateTime(new Date());

        ParkInfo parkInfo = parkInfoService.getParkInfoByParkCode();
        // 如果计费版本是新版
        if (JddConstant.ParkInfoConstant.CHARGE_FEE_EDITION.equals(parkInfo.getChargeFeeEdition())) {
            if (StringUtils.isBlank(parkSpace.getAreaId())) {
                return result.error500("大小车场模式，请配置车位所在区域");
            }
        }
        LambdaQueryWrapper<ParkSpace> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkSpace::getParkNumber, parkSpace.getParkNumber());
        List<ParkSpace> list = parkSpaceService.list(queryWrapper);

        if (list.size() > 0) {
            return result.error500("该车位已存在");
        }
        // 车位的车辆停驶状态，只有在添加的时候初始化为0，编辑和删除
        parkSpace.setParkStatus("0");
        Boolean ok = parkSpaceService.save(parkSpace);
        log.info("车位新增结果：" + ok);
        if (ok) {
            return result.success("新增成功");
        } else {
            return result.error500("新增失败");
        }
    }

    @AutoLog(value = "车位管理-编辑车位")
    @ApiOperation(value = "车位管理-编辑车位", notes = "车位管理-编辑车位")
    @PostMapping(value = "/edit")
    @OperationLogDetail(detail = "车位管理，车位编辑", level = LogLevelType.ONE, operationType = OperationType.UPDATE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> edit(@RequestBody ParkSpace parkSpace) {
        Result<?> result = new Result<>();
        ParkSpace space = parkSpaceService.getById(parkSpace.getId());
        String userName = parkSpace.getUserName();
        String mobile = parkSpace.getMobile();
        String address = parkSpace.getAddress();
        Integer payFee = parkSpace.getPayFee();
        if (space == null) {
            return result.error500("该车位纪录不存在");
        } else {
            space.setUserName(userName);
            space.setMobile(mobile);
            space.setAddress(address);
            space.setPayFee(payFee);
            space.setParkSpaceRemark(parkSpace.getParkSpaceRemark());
            LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkCarMonthly::getParkNumber, space.getParkNumber());
            List<ParkCarMonthly> list = parkCarMonthlyService.list(queryWrapper);
            for (int i = 0; i < list.size(); i++) {
                ParkCarMonthly parkCarMonthly = list.get(i);
                parkCarMonthly.setUserName(userName);
                parkCarMonthly.setMobile(mobile);
                parkCarMonthly.setAddress(address);
                parkCarMonthly.setPayFee(payFee);
            }
            boolean isParkCarMonthlyListUpdateOk = parkCarMonthlyService.updateBatchById(list);
            if (isParkCarMonthlyListUpdateOk) {
                boolean isParkSpaceUpdateOk = parkSpaceService.updateById(space);
                if (isParkSpaceUpdateOk) {
                    return result.success("编辑车位信息成功");
                }
                return result.error500("车位信息编辑失败");
            } else {
                return result.error500("月租车信息更新失败");
            }
        }
    }
    @AutoLog(value = "车位管理-根据id获取车位信息")
    @ApiOperation(value = "车位管理-根据id获取车位信息", notes = "车位管理-根据id获取车位信息")
    @OperationLogDetail(detail = "车位管理-根据id获取车位信息")
    @GetMapping(value = "/queryById")
    public Result<ParkSpace>queryById(@RequestParam("id")String id){
        Result<ParkSpace> result=new Result<>();
        ParkSpace parkSpace = parkSpaceService.getById(id);
        result.setSuccess(true);
        result.setResult(parkSpace);
        result.setMessage("查询成功");
        return result;
    }
    @AutoLog(value = "车位管理-绑定车位与车牌号")
    @ApiOperation(value = "车位管理-绑定车位与车牌号", notes = "车位管理-绑定车位与车牌号")
    @PostMapping(value = "/bindPlateNo")
    @OperationLogDetail(detail = "车位管理，车位与车牌号绑定", level = LogLevelType.ONE, operationType = OperationType.INSERT, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> bindPlateNo(@RequestBody ParkSpaceBindPlateNoVO parkSpaceBindPlateNoVo) {
        Result<ParkCarMonthly> result = new Result<ParkCarMonthly>();
        ParkCarMonthly parkCarMonthly = parkSpaceBindPlateNoVo.getParkCarMonthly();
        try {
            ConfigParkInfo configParkInfo = configParkInfoService.findConfigParkInfoByParkCode();
            if (ObjectUtil.isNull(configParkInfo)) {
                return Result.error(510, "车辆信息配置为空，请检查");
            }
            if (!PlateNoCheckUtil.checkPlateNo(parkCarMonthly.getPlateNo())) {
                // 若格式错误，则返回错误信息
                return Result.error(510, "车牌号错误");
            }
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            parkCarMonthly.setParkCode(configParkInfo.getParkCode());
            parkCarMonthly.setParkName(configParkInfo.getParkName());
            LambdaQueryWrapper<ParkCarMonthly> carCheckQueryWrapper = new LambdaQueryWrapper<>();
            carCheckQueryWrapper.eq(ParkCarMonthly::getParkCode, parkCarMonthly.getParkCode());
            carCheckQueryWrapper.eq(ParkCarMonthly::getParkNumber, parkCarMonthly.getParkNumber());
            // 查询是否在同一车场下，有相同车牌号的数据
            List<ParkCarMonthly> carList = parkCarMonthlyService.list(carCheckQueryWrapper);
            if (carList.size() == PARK_SPACE_BIND_MAX_NUMBER) {
                return result.error500("该车位可绑定的车牌号数量已达到最大值");
            }
            if (carList.stream().anyMatch(carMonthly -> carMonthly.getPlateNo().equals(parkCarMonthly.getPlateNo()))) {
                return result.error500("请勿重复绑定");
            }
            result = updateParkSpace(parkSpaceBindPlateNoVo.getParkSpaceRemark(), parkCarMonthly);
            if (result.getCode().equals(ERROR_CODE_500)) {
                return result;
            }
            carCheckQueryWrapper = new LambdaQueryWrapper<>();
            carCheckQueryWrapper.eq(ParkCarMonthly::getParkCode, parkCarMonthly.getParkCode());
            carCheckQueryWrapper.eq(ParkCarMonthly::getPlateNo, parkCarMonthly.getPlateNo());
            List<ParkCarMonthly> list = parkCarMonthlyService.list(carCheckQueryWrapper);
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setCarTypeId(parkCarMonthly.getCarTypeId());
            }
            parkCarMonthly.setId(SnowFlakeUtil.getId());
            parkCarMonthly.setCreateTime(new Date());
            parkCarMonthly.setCreateUser(loginUser.getUsername());
            parkCarMonthlyService.save(parkCarMonthly);
            if (list.size() > 0) {
                parkCarMonthlyService.updateBatchById(list);
            }
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }
    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsNew")
    public ModelAndView exportXlsNew(HttpServletRequest request, HttpServletResponse response, ParkSpace parkSpace) {
        // Step.1 组装查询条件
        QueryWrapper<ParkSpace> queryWrapper = QueryGenerator.initQueryWrapper(parkSpace, request.getParameterMap());
        queryWrapper.orderByDesc("park_status");
        queryWrapper.orderByAsc("park_number");
        queryWrapper.orderByDesc("create_time");
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
        List<ParkSpace> pageList = parkSpaceService.list(queryWrapper);
        for (ParkSpace space:pageList){
            if(null!=space.getParkStatus())
            {
                switch (space.getParkStatus())
                {
                    case "0":space.setParkStatus("空闲");break;
                    case "1":space.setParkStatus("占用");break;
                    default:space.setParkStatus("未知");break;
                }
            }
            if(null!=space.getSpaceType())
            {
                switch (space.getSpaceType())
                {
                    case "1":space.setSpaceType("标准车位");break;
                    case "2":space.setSpaceType("子母车位");break;
                    case "3":space.setSpaceType("预约车位");break;
                    default:space.setSpaceType("未知");break;
                }
            }
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "车位管理表");
        mv.addObject(NormalExcelConstants.CLASS, ParkSpace.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("车位管理表列表数据", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }
    @AutoLog(value = "车位管理-车位延期")
    @ApiOperation(value = "车位管理-车位延期", notes = "车位管理-车位延期")
    @PostMapping(value = "/delay")
    @OperationLogDetail(detail = "车位管理，车位延期", level = LogLevelType.ONE, operationType = OperationType.UPDATE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> delay(@RequestBody ParkSpace parkSpace) {
        Result<ParkSpace> result = new Result<>();
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        ParkSpace space = parkSpaceService.getById(parkSpace.getId());
        ParkWhiteEditList parkWhiteEditList = new ParkWhiteEditList();
        parkWhiteEditList.setId(SnowFlakeUtil.getId());
        parkWhiteEditList.setPlateNo(space.getParkNumber());
        parkWhiteEditList.setParkNumber(space.getParkNumber());
        parkWhiteEditList.setParkCode(loginUser.getParkCode());
        parkWhiteEditList.setParkName(loginUser.getParkName());
        parkWhiteEditList.setOptionsType(2);
        parkWhiteEditList.setStartTime(space.getStartTime());
        parkWhiteEditList.setUserName(space.getUserName());
        parkWhiteEditList.setMobile(space.getMobile());
        parkWhiteEditList.setAddress(space.getAddress());
        parkWhiteEditList.setRemark(space.getParkSpaceRemark());
        parkWhiteEditList.setUpdateUser(loginUser.getUsername());
        parkWhiteEditList.setBeforeEntTime(space.getEndTime());
        parkWhiteEditList.setEndTime(space.getEndTime());
        parkWhiteEditList.setUpdateTime(new Date());
        parkWhiteEditList.setCreateTime(new Date());
        parkWhiteEditList.setCreateUser(loginUser.getUsername());
        parkWhiteEditList.setLicenseType(1);
        space.setEndTime(parkSpace.getEndTime());
        LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkCarMonthly::getParkCode, loginUser.getParkCode());
        queryWrapper.eq(ParkCarMonthly::getParkNumber, space.getParkNumber());
        List<ParkCarMonthly> list = parkCarMonthlyService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setEndTime(parkSpace.getEndTime());
        }

        Boolean isParkSpaceUpdateOk = parkSpaceService.updateById(space);
        if (isParkSpaceUpdateOk) {
            Boolean isParkCarMonthlyUpdateOk = parkCarMonthlyService.updateBatchById(list);
            if (isParkCarMonthlyUpdateOk) {
                Boolean isParkWhiteEditSaveOk = parkWhiteEditListService.save(parkWhiteEditList);
                if (isParkWhiteEditSaveOk) {
                    return result.success("延期成功");
                } else {
                    return result.error500("延期成功，但纪录保存失败");
                }
            } else {
                return result.error500("延期失败");
            }
        }
        return result.error500("延期失败");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车位管理-通过id删除车位")
    @ApiOperation(value = "车位管理-通过id删除", notes = "车位管理-通过id删除")
    @DeleteMapping(value = "/delete")
    @OperationLogDetail(detail = "车位管理，车位通过id删除", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            ParkSpace parkSpace = parkSpaceService.getById(id);
            LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            queryWrapper.eq(ParkCarMonthly::getParkNumber, parkSpace.getParkNumber());
            parkCarMonthlyService.remove(queryWrapper);
            parkSpaceService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    @AutoLog(value = "车位管理-通过id删除月租车信息")
    @ApiOperation(value = "车位管理-通过id删除", notes = "车位管理-通过id删除")
    @DeleteMapping(value = "/removeBindCar")
    @OperationLogDetail(detail = "车位管理，通过id删除月租车信息", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> removeBindCar(@RequestParam(name = "id", required = true) String id) {
        try {
            ParkCarMonthly parkCarMonthly = parkCarMonthlyService.getById(id);
            parkCarMonthlyService.removeById(id);
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            // 查询该月租车信息所绑定的车位下，是否还绑定有其他车辆
            LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkCarMonthly::getParkNumber, parkCarMonthly.getParkNumber());
            List<ParkCarMonthly> parkCarMonthlyList = parkCarMonthlyService.list(queryWrapper);
            if (parkCarMonthlyList.size() == 0) {
                LambdaQueryWrapper<ParkSpace> parkSpaceQueryWrapper = new LambdaQueryWrapper<>();
                parkSpaceQueryWrapper.eq(ParkSpace::getParkCode, parkCarMonthly.getParkCode());
                parkSpaceQueryWrapper.eq(ParkSpace::getParkNumber, parkCarMonthly.getParkNumber());
                ParkSpace parkSpace = resetParkSpace(parkSpaceService.getOne(parkSpaceQueryWrapper));
                parkSpaceService.removeById(parkSpace.getId());
                parkSpaceService.save(parkSpace);
                Result<ParkSpace> result = new Result<>();
                result.setResult(parkSpace);
                return result;
            }
            return Result.ok("删除成功!");
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }

    }

    @AutoLog(value = "车位管理-批量删除车位信息")
    @ApiOperation(value = "车位管理-批量删除车位信息", notes = "车位管理-批量删除车位信息")
    @OperationLogDetail(detail = "车位管理-批量删除车位信息", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    @DeleteMapping(value = "/removeByBatch")
    public Result<?> removeByBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ParkSpace> result = new Result<ParkSpace>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            List<String> idList = Arrays.asList(ids.split(","));
            List<String> parkNumberList = parkSpaceService.listByIds(idList).stream().map(ParkSpace::getParkNumber).collect(Collectors.toList());
            List<CompletableFuture<Boolean>> futureList = new ArrayList<>();
            int pageSize = 50;
            int pageNumber = parkNumberList.size() / pageSize;
            for (int index = 0; index <= pageNumber; index++) {
                List<String> parkNumberListPage;
                if (index == pageNumber) {
                    parkNumberListPage = parkNumberList.subList(index * pageSize, parkNumberList.size());
                } else {
                    parkNumberListPage = parkNumberList.subList(index * pageSize, (index + 1) * pageSize);
                }
                CompletableFuture<Boolean> completableFuture = CompletableFuture.supplyAsync(() -> {
                    return removeParkCarMonthlyByParkSpace(parkNumberListPage);
                }, executorService);
                futureList.add(completableFuture);
            }
            CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
            boolean parkSpaceRemove = parkSpaceService.removeByIds(idList);
            if (parkSpaceRemove) {
                return result.success("删除成功");
            }
        }
        return result.error500("删除失败");
    }


    /**
     * 场端一键同步云端月租车信息
     *
     * @param
     * @return com.jdd.common.api.vo.Result<?>
     * @author jdd孙庆伟
     * @date 2021/10/15 09:48:40
     * @version 1.0
     */
    @AutoLog(value = "月租车位-同步云端月租车信息")
    @ApiOperation(value = "月租车位-同步云端月租车信息", notes = "月租车位-同步云端月租车信息")
    @PostMapping(value = "/synchronizeSpaceInfo")
    @OperationLogDetail(detail = "月租车位-同步云端月租车信息", level = LogLevelType.ONE, operationType = OperationType.UPDATE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> synchronizeSpaceInfo() {
        RestTemplateVo restTemplateVo = new RestTemplateVo();
        restTemplateVo.setParkCode(parkCode);
        String url = "";
        ResultVo<?> body;
        try {
            body = GuavaRetryingUtils.restTemplatePosts(restTemplateVo, url, restTemplateUtils, appId, appScrect);
        } catch (Exception e) {
            log.error("获取云端数据失败，异常信息：{}", e.getMessage());
            return Result.error("获取云端数据失败");
        }
        CloudSynParkSpaceVo cloudSynParkSpaceVo;
        try {
            String dataStr = String.valueOf(body.getData());
            cloudSynParkSpaceVo = JSONObject.parseObject(dataStr, CloudSynParkSpaceVo.class);
        } catch (Exception e) {
            log.error("解析云端数据失败，异常信息：{}", e.getMessage());
            return Result.error("解析云端数据失败");
        }
        try {
            List<ParkSpace> parkSpaces = cloudSynParkSpaceVo.getParkSpaces();
            List<ParkCarMonthly> parkCarMonthlyList = cloudSynParkSpaceVo.getParkCarMonthlyList();
            List<ParkWhiteEditList> parkWhiteEditLists = cloudSynParkSpaceVo.getParkWhiteEditLists();

            //清空月租车位信息
            parkSpaceService.removeAllInfo();
            //保存云端月租车位信息
            parkSpaceService.saveBatch(parkSpaces);

            //清空月租车信息
            parkCarMonthlyService.removeAllInfo();
            //保存云端月租车信息
            parkCarMonthlyService.saveBatch(parkCarMonthlyList);

            //清空延期表
            parkWhiteEditListService.removeAllInfo();
            //保存云端延期表数据
            parkWhiteEditListService.saveBatch(parkWhiteEditLists);
        } catch (Exception e) {
            log.error("保存云端数据失败，异常信息：{}", e.getMessage());
            return Result.error("保存云端数据失败");
        }
        return Result.ok("同步云端数据成功");
    }

    private Result<ParkCarMonthly> updateParkSpace(String remark, ParkCarMonthly parkCarMonthly) {
        Result<ParkCarMonthly> result = new Result<>();
        LambdaQueryWrapper<ParkSpace> parkSpaceQueryWrapper = new LambdaQueryWrapper<>();
        parkSpaceQueryWrapper.eq(ParkSpace::getParkNumber, parkCarMonthly.getParkNumber());
        ParkSpace parkSpace = parkSpaceService.getOne(parkSpaceQueryWrapper);
        // 如果该车位之前绑定有车辆
        if (ObjectUtil.isNotNull(parkSpace) && ObjectUtil.isNotNull(parkSpace.getUserName())) {
            // 如果绑定的用户信息与绑定的月租车的用户信息不一致
            if (!parkSpace.getUserName().equals(parkCarMonthly.getUserName())) {
                return result.error500("与之前绑定的用户信息不一致");
            }
        } else {
            parkSpace.setUserName(parkCarMonthly.getUserName());
        }
        parkSpace.setStartTime(parkCarMonthly.getStartTime());
        parkSpace.setEndTime(parkCarMonthly.getEndTime());
        parkSpace.setPayFee(parkCarMonthly.getPayFee());
        parkSpace.setUserName(parkCarMonthly.getUserName());
        parkSpace.setMobile(parkCarMonthly.getMobile());
        parkSpace.setAddress(parkCarMonthly.getAddress());
        parkSpace.setParkSpaceRemark(remark);
        parkSpace.setStatus(parkCarMonthly.getStatus());
        parkSpace.setUpdateTime(new Date());
        Boolean ok = parkSpaceService.updateById(parkSpace);
        if (ok) {
            return result.success("更新车位成功");
        } else {
            return result.error500("更新车位失败");
        }

    }

    private ParkSpace resetParkSpace(ParkSpace parkSpace) {
        parkSpace.setParkStatus("0");

        parkSpace.setStartTime(null);
        parkSpace.setEndTime(null);
        parkSpace.setPayFee(null);
        parkSpace.setUserName(null);
        parkSpace.setAddress(null);
        parkSpace.setMobile(null);
        parkSpace.setParkSpaceRemark(null);
        return parkSpace;
    }

    private boolean removeParkCarMonthlyByParkSpace(List<String> parkNumberList) {
        LambdaQueryWrapper<ParkCarMonthly> queryWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isNotEmpty(parkNumberList)) {
            queryWrapper.in(ParkCarMonthly::getParkNumber, parkNumberList);
            return parkCarMonthlyService.remove(queryWrapper);
        } else {
            return false;
        }
    }
}
